from datetime import datetime
from typing import Optional
from beanie import Document
from pydantic import Field, field_serializer

"""
这个是微信扫码登录的用户
"""
class WxUser:
    user_id: str = Field(..., description="用户ID")
    device_id: str = Field(..., description="设备ID")
    nickname: str = Field(..., description="昵称")
    auth_key: str = Field(..., description="授权密钥")
    avatar: Optional[str] = Field(default=None, description="头像URL")
    ip: Optional[str] = Field(default=None, description="IP地址")
    status: int = Field(..., description="用户状态")
    expire_time: datetime = Field(default_factory=lambda: datetime.now())
    is_rag:bool = Field(default=False, description="是否 rag")

class WxUserModel(Document,WxUser):

    created_at: datetime = Field(default_factory=lambda: datetime.now())
    updated_at: datetime = Field(default_factory=lambda: datetime.now())
    login_at: datetime = Field(default_factory=lambda: datetime.now())
    is_active: bool = True



    class Settings:
        name = "wx_users"  # 自定义集合名称为 "users"
        validate_on_save = True  # 保存时验证
        use_revision = True  # 启用版本控制
        bson_encoders = {
            datetime: lambda dt: dt.isoformat()  # 自定义编码器
        }

    @field_serializer('created_at', 'updated_at', 'login_at')
    def format_datetime(self, value: datetime) -> str:
        return value.strftime("%Y-%m-%d %H:%M:%S")

    # 更新时自动更新时间戳
    async def before_update(self):
        self.updated_at = datetime.utcnow()


    @classmethod
    async def exists(cls, **kwargs) -> bool:
        count = await cls.find(kwargs).limit(1).count()
        return count > 0
